package com.bank.abmock.boot;

import com.alibaba.fastjson.JSON;
import com.bank.abmock.config.JsonRouteConfig;
import com.bank.abmock.config.RouteConfig;
import com.bank.abmock.config.XmlRouteConfig;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Component
public class XmlConfigLoad extends LoadConfig {

    private final ResourceLoader resourceLoader;

    @Override
    @PostConstruct
    public List<RouteConfig> loadConfig() {
        //TODO 加载整个目录下的文件
        log.debug("开始加载模板xml文件 ...");
        try{
            String pattern = "classpath:XmlTemplate/*.xml";
            Resource[] xmlResources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources(pattern);
            List<RouteConfig> routeConfigList = new ArrayList<>();
            for (Resource resource : xmlResources) {
                String filename = resource.getFilename();
                if (filename.endsWith(".xml")){
                    InputStream xmlInputStream = resource.getInputStream();
                    String text = IOUtils.toString(xmlInputStream,"utf-8");
                    XmlMapper xmlMapper = new XmlMapper();
                    XmlRouteConfig routeConfig= xmlMapper.readValue(text, XmlRouteConfig.class);
                    routeConfigList.add(routeConfig);
                }
            }
            routeMapperCenter.register(routeConfigList);
            return routeConfigList;
        } catch (IOException e){
            System.out.println(e);
        }
        return null;

    }

}
